//
//  SWPageEditorViewController.swift
//  YiyaPuzzleDemo
//
//  Created by linhan on 16/10/27.
//  Copyright © 2016年 test. All rights reserved.
//

import Foundation
import UIKit
class SWBookViewController: SWBaseViewController,SWBookPageEditorDelegate,UITableViewDataSource,UITableViewDelegate,PulldownContainerDelegate
{
    var navIndex:Int = 0
    var bookID:String = ""
    var pageID:String = ""
    
    private var _index:Int = 0
    private var _book:SWBook?
    private var _books:[SWBook] = []
    private var _pages:[SWPage] = []
    //一本书总的页数
    private var _pageTotalCount:Int = 0
    //一本书已开启的页数
    private var _pageEnableCount:Int = 0
    
    private var _pageEditor:SWBookPageEditor?
    
    private var _nullDataView:UIView?
    private var _container:UIView = UIView()
    
    lazy private var _pulldownContainer:PulldownContainer = PulldownContainer()
    lazy private var _headerView:SWBooksHeaderView = SWBooksHeaderView()
    lazy private var _tableView:UITableView = UITableView()
    
    private var _countLabel:UILabel = UILabel()
    private var _titleLabel:UILabel = UILabel()
    private var _dateLabel:UILabel = UILabel()
    private var _newIcon:UILabel = UILabel()
    
    deinit
    {
        print("DEINIT SWBookViewController")
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        setup()
    }
    
    override func viewWillDisappear(_ animated: Bool)
    {
        super.viewWillDisappear(animated)
        if _pulldownContainer.state != .closed
        {
            _pulldownContainer.close(false)
        }
    }
    
    private func setup()
    {
        automaticallyAdjustsScrollViewInsets = false
        view.backgroundColor = UIColor(white: 0.95, alpha: 1)
        
        createNavigationRightButton("打印", target: self, action: #selector(previewBtnTapped))
        createHeaderView()
        
        _nullDataView = createNullDataView()
        
        _container.frame = view.bounds
        _container.isHidden = true
        view.addSubview(_container)
        
        //TopView
        let lastY = createTopToolbar(y: navigationBarBottom)
        let bottomToolbarHeight:CGFloat = createBottomToolbar()
        
        //翻页
        createPageView(topMargin:lastY, bottomMargin:bottomToolbarHeight)
        
        //取出事件类型的书
        _books = SWBookManager.sharedManager().books.filter({$0.category == .event})
        
        var bookIndex = 0
        if let index = _books.index(where: {($0.bookID ?? "") == bookID}),bookID != ""
        {
            bookIndex = index
        }
        
        if let book = _books.valueAt(bookIndex)
        {
            showBook(book)
            if pageID != ""
            {
                if let pages:[SWPage] = book.pages?.flatMap({$0 as? SWPage}),
                   let index = pages.index(where: {($0.pageID ?? "") == pageID})
                {
                    setTimeout(0.5, closure: {[weak self] in
                        self?._pageEditor?.jumbIndex(index:index, animated:true)
                    })
                }
            }
        }
        else
        {
            _container.isHidden = true
        }
        
        
        let count:Int = _books.count
        let TableViewHeight:CGFloat = min(self.view.height - navigationBarBottom, SWThemeStyle.BookCellHeight * CGFloat(count))
        _tableView.height = TableViewHeight
        _pulldownContainer.content = _tableView
        
    }
    
    //翻页组件
    private func createPageView(topMargin:CGFloat, bottomMargin:CGFloat)
    {
        let PageViewInsets:UIEdgeInsets = UIEdgeInsetsMake(topMargin, 0, bottomMargin, 0)
        let ContainerSize = CGSizeMake(view.width - PageViewInsets.left - PageViewInsets.right, view.height - PageViewInsets.top - PageViewInsets.bottom)
        let BookFullPageSize = SW.Config.BookSinglePageSize
        let scale:CGFloat = ViewUtil.getAdaptiveScale(BookFullPageSize.width, targetH: BookFullPageSize.height, containerW: ContainerSize.width, containerH: ContainerSize.height)
        let PageViewSize = CGSizeMake(BookFullPageSize.width * scale, BookFullPageSize.height * scale)
        let PageViewX:CGFloat = PageViewInsets.left + (ContainerSize.width - PageViewSize.width) * 0.5
        let PageViewY:CGFloat = PageViewInsets.top + (ContainerSize.height - PageViewSize.height) * 0.5
        let PageViewRect = CGRectMake(PageViewX, PageViewY, PageViewSize.width, PageViewSize.height)
        
        
        let pageEditor:SWBookPageEditor = SWBookPageEditor(frame:PageViewRect)
        pageEditor.delegate = self
        _container.addSubview(pageEditor)
        _pageEditor = pageEditor
    }
    
    private func createHeaderView()
    {
        let tapGesture:UITapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(headerViewTapped))
        _headerView.addGestureRecognizer(tapGesture)
        navigationItem.titleView = _headerView
        let rowHeight:CGFloat = SWThemeStyle.BookCellHeight
        
        _pulldownContainer.modelInsets = UIEdgeInsetsMake(navigationBarBottom, 0, 0, 0)
        _pulldownContainer.offset = CGPointMake(0, navigationBarBottom)
        _pulldownContainer.delegate = self
        
        _tableView.frame = CGRectMake(0, 0, view.width, 0)
        _tableView.tableFooterView = UIView()
        _tableView.dataSource = self
        _tableView.delegate = self
        _tableView.backgroundColor = UIColor(hex: 0xeceeef)
        _tableView.rowHeight = rowHeight
        //_tableView.separatorColor = ThemeStyle.TableViewSeparatorColor
        _tableView.separatorInset = UIEdgeInsets.zero
        if #available(iOS 8.0, *) {
            _tableView.layoutMargins = UIEdgeInsets.zero
        }
    }
    
    private func createTopToolbar(y:CGFloat) -> CGFloat
    {
        let toolbar:UIView = UIView()
        toolbar.frame = CGRectMake(0, y, view.width, 40)
        toolbar.backgroundColor = UIColor(white: 0.97, alpha: 1)
        _container.addSubview(toolbar)
        
        _countLabel.frame = CGRectMake(0, 0, 30, toolbar.height)
        _countLabel.textColor = UIColor.darkGray
        toolbar.addSubview(_countLabel)
        
        let dateLabelWidth:CGFloat = 90
        _dateLabel.frame = CGRectMake(toolbar.width - dateLabelWidth, 0, dateLabelWidth, toolbar.height)
        _dateLabel.textColor = UIColor.darkGray
        _dateLabel.textAlignment = .right
        toolbar.addSubview(_dateLabel)
        
        let titleLabelGrid:CGFloat = 10
        let titleLabelWidth:CGFloat = _dateLabel.x - _countLabel.right - 2 * titleLabelGrid
        _titleLabel.frame = CGRectMake(_countLabel.right + titleLabelGrid, 0, titleLabelWidth, toolbar.height)
        _titleLabel.textColor = UIColor.darkGray
        toolbar.addSubview(_titleLabel)
        
        _newIcon.text = "NEW"
        _newIcon.sizeToFit()
        _newIcon.isHidden = true
        _newIcon.frame = CGRectMake(_titleLabel.right, _titleLabel.y, _newIcon.width, _newIcon.height)
        toolbar.addSubview(_newIcon)
        
        
        return toolbar.bottom
    }
    
    private func createBottomToolbar() -> CGFloat
    {
        let barHeight:CGFloat = 40
        let bar = UIView()
        bar.backgroundColor = UIColor.lightGray
        bar.frame = CGRectMake(0, view.height - barHeight, view.width, barHeight)
        view.addSubview(bar)
        return barHeight
    }
    
    private func createNullDataView() -> UIView
    {
        let dataView:UIView = UIView()
        dataView.frame = CGRectMake(0, 0, view.width, 150)
        dataView.center = view.center
        view.addSubview(dataView)
        
        let label:UILabel = UILabel()
        label.text = "还没有生成新的故事哟"
        label.textColor = UIColor.darkGray
        label.sizeToFit()
        label.frame = CGRectMake((dataView.width - label.width) * 0.5, 0, label.width, label.height)
        dataView.addSubview(label)
        
        let button:UIButton = UIButton(type: .system)
        button.setTitle("去大事件", for: .normal)
        button.sizeToFit()
        button.frame = CGRectMake((dataView.width - button.width) * 0.5, dataView.height - button.height, button.width, button.height)
        button.addTarget(self, action: #selector(navigationBtnTapped), for: .touchUpInside)
        dataView.addSubview(button)
        
        return dataView
    }
    
    private func showBook(_ book:SWBook)
    {
        _index = 0
        _book = book
        _headerView.name = book.title
        SWBookManager.sharedManager().editingBook(book)
        if let pages = book.pages?.flatMap({$0 as? SWPage}),pages.count > 0
        {
            _pages.removeAll()
            
            for page in pages
            {
                let eventID = page.eventID ?? ""
                if SWAssetsManager.sharedManager().assets.filter({($0.eventID ?? "") == eventID}).count > 0
                {
                    _pages.append(page)
                    page.loadPhotoFromEvent()
                }
            }
            if true
            {
                _pages = pages
            }
            
            _pageEnableCount = _pages.count
            _pageTotalCount = pages.count
            _pageEditor?.reloadData(pages: _pages, index:0)
            
            pageShowed(index: _index)
        }
        //本相册无照片
        _container.isHidden = _pages.count == 0
    }
    
    private func pageShowed(index: Int)
    {
        if let page = _pages.valueAt(index)
        {
            _titleLabel.text = page.title ?? ""
            _countLabel.text = "\(_index + 1)/\(_pageTotalCount)"
            _newIcon.isHidden = !page.importedFirstTime
            if page.importedFirstTime
            {
                page.importedFirstTime = false
            }
            //显示最早添加到此事件的时间
            let importedTime:Int = page.photoImportedTime
            if importedTime > 0
            {
                let date:NSDate = Date(timeIntervalSince1970: TimeInterval(importedTime)) as NSDate
                _dateLabel.text = date.formattedDate(withFormat: "MM月-dd日")
            }
        }
    }
    
    func bookPageEditor(editor:SWBookPageEditor, didScrollToIndex index: Int)
    {
        _index = index
        pageShowed(index: index)
    }
    
    func willPresentPulldownContainer()
    {
        _headerView.open()
    }
    
    func willDismissPulldownContainer()
    {
        _headerView.close()
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell
    {
        let Identifier:String = "SWBookCell"
        var cell:UITableViewCell? = tableView.dequeueReusableCell(withIdentifier: Identifier) as? SWBookCell
        if cell == nil
        {
            cell = SWBookCell(style: .default, reuseIdentifier: Identifier, cellWidth: view.width)
        }
        (cell as? SWBookCell)?.book = _books.valueAt(indexPath.row)
        return cell ?? UITableViewCell()
    }
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int
    {
        return _books.count
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath)
    {
        tableView.deselectRow(at: indexPath, animated: true)
        if let book = _books.valueAt(indexPath.row)
        {
            showBook(book)
        }
        _pulldownContainer.close()
    }
    
    
    //提交前进行空白页、空白格检查
    @objc private func commitBtnTapped()
    {
        
    }
    
    @objc private func previewBtnTapped()
    {
//        if let book = _book
//        {
//            let viewController = SWPreviewViewController(book: book)
//            viewController.currIndex = _index
//            present(viewController, animated: true, completion: nil)
//        }
        
        navigationController?.pushViewController(SWBasketViewController(), animated: true)
        //navigationController?.pushViewController(SWBookIntroduceViewController(), animated: true)
    }
    
    @objc private func headerViewTapped()
    {
        if _pulldownContainer.state == .closing || _pulldownContainer.state == .opening
        {
            return
        }
        
        if _pulldownContainer.state == .closed
        {
            _pulldownContainer.open()
        }
        else
        {
            _pulldownContainer.close()
        }
    }
    
    @objc private func navigationBtnTapped()
    {
        NotificationCenter.default.post(name: NotificationName.Navigation, object: nil, userInfo: [SWKey.ViewController:"SWEventsViewController"])
        navigationController?.popToRootViewController(animated: true)
    }
    
    
    
    
}
